package com.fh.controller.property;

import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.entity.system.User;
import com.fh.service.building.RecordService;
import com.fh.service.property.PropertyService;
import com.fh.util.Const;
import com.fh.util.DateUtil;
import com.fh.util.JSONHelper;
import com.fh.util.PageData;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

import static com.fh.controller.system.tools.GetDatalayui.getLData;
import static com.fh.controller.system.tools.GetDatalayui.getPData;

/**
 * Created by lr on 2017/10/30.
 */
@Controller
@RequestMapping(value = "/property")
public class PropertyController extends BaseController {
    @Resource(name = "propertyService")
    private PropertyService propertyService;
    @Resource(name = "recordService")
    private RecordService recordService;

    /**
     * 物业设置 list列表
     */
    @RequestMapping(value = "/listProperty")
    @ResponseBody
    public Object json(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            pd = this.getPageData();
            pd.put("USER_ID", user.getUSER_ID());
            getPData(page, pd);
            varList = propertyService.listAllproperty(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }



    /**
     * 通过ID获取详情信息设置详情
     */
    @RequestMapping(value = "/propertyinfo")
    @ResponseBody
    public PageData Propertyinfo() {
        logBefore(logger, "设置详情");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            PageData data = propertyService.findPropertyById(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 新增物业设置和批量新增价格
     */
    @RequestMapping(value = "/savePropertyAndPrice")
    @ResponseBody
    public PageData saveproperty() {
        logBefore(logger, "新增property");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            String IDS = this.get32UUID();//物业设置的ID
            String CREATETIME = new DateUtil().getTime();//创建时间

             /*String CHARGE_TYPES = "";
            String CHARGE_DATES = "";*/

            /*if(pd.get("data1[gdsr]") !=null && !"".equals(pd.get("data1[gdsr]"))){

                CHARGE_TYPES +=(pd.get("data1[gdsr]"));


            } if (pd.get("data1[cbsf]") !=null && !"".equals(pd.get("data1[cbsf]"))){

                CHARGE_TYPES +=(pd.get("data1[cbsf]"));

            } if (pd.get("data1[mjsf]") !=null && !"".equals(pd.get("data1[mjsf]"))){

                CHARGE_TYPES +=(pd.get("data1[mjsf]"));

            } if (pd.get("data1[tqrsf]") !=null && !"".equals(pd.get("data1[tqrsf]"))){

                CHARGE_DATES +=(pd.get("data1[tqrsf]"));

            } if (pd.get("data1[gdrsf]") !=null && !"".equals(pd.get("data1[gdrsf]"))){

                CHARGE_DATES +=(pd.get("data1[gdrsf]"));

            } if (pd.get("data1[cbhsf]") !=null && !"".equals(pd.get("data1[cbhsf]"))){

                CHARGE_DATES +=(pd.get("data1[cbhsf]"));

            }*/

            //CHARGE_TYPES=CHARGE_TYPES.substring(0,CHARGE_TYPES.length()-1);
            //CHARGE_DATES=CHARGE_DATES.substring(0,CHARGE_DATES.length()-1);

            PageData property = new PageData();//物业设置
            property.put("ID", IDS);//物业设置主键
            property.put("CODE", pd.get("data1[CODE]")); //物业类型名称
           /* property.put("CHARGE_DATE", CHARGE_DATES); //物业创建时间*/
           /* property.put("CHARGE_TYPE",CHARGE_TYPES ); //物业收费类型*/
            property.put("INFO", pd.get("data1[INFO]")); //备注
            property.put("CREATE_PERSON_ID", user.getUSER_ID()); //用户ID
            property.put("CREATE_DATE", CREATETIME); //用户创建时间
            property.put("IS_OPEN", pd.get("data1[IS_OPEN]")); //是否开启
            property.put("PROPERTY_TYPE",1);
            property.put("IS_DEL",0);
            propertyService.savePropertySet(property);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","新增物业数据");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",property.toString());
            recordService.SaveSystem(SystemPd);

            PageData price = new PageData();//物业价格
            //获得jsonArray的第一个元素
            JSONArray jsonArray = JSONArray.fromObject(pd);
            Object o2 = jsonArray.get(0);
            JSONObject jsonObject2 = JSONObject.fromObject(o2);
            //JSONHelper.json2Map(jsonObject2.get("sendData[DATA]").toString());
            Map map2 = JSONHelper.json2Map(jsonObject2.get("DATAS[DATA]").toString());
            Set<Object> keySet2 = map2.keySet();
            //有了Set集合。就可以获取其迭代器。
            Iterator<Object> it2 = keySet2.iterator();
            while (it2.hasNext()) {
                Object key = it2.next();
                //有了键可以通过map集合的get方法获取其对应的值。
                Object value = (Object) map2.get(key);
                List<PageData> list2 = (List<PageData>) JSONArray.toList(JSONArray.fromObject(value.toString()), PageData.class);
                for (PageData stu : list2) {
                    price.put("ID", this.get32UUID());//物业设置主键
                    price.put("IS_DEL", 0); //是否删除
                    price.put("SORT", 0); //排序
                    price.put("CREATE_ID", user.getUSER_ID()); //用户ID
                    price.put("CREATE_DATE", CREATETIME); //创建时间
                    price.put("PRICE_NAME", stu.get("PRICE_NAME").toString());//价格名称
                    price.put("PRICE_TYPE", stu.get("PRICE_TYPE").toString());//价格
                    //price.put("PRICE_CURRENCY", stu.get("PRICE_CURRENCY").toString());//价格类型
                    price.put("PROPERTY_SET_ID", IDS);//物业设置ID
                    propertyService.savePropertyPrice(price);
                }
            }
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 编辑物业设置和批量设置价格
     */
    @RequestMapping(value = "/editPropertyAndPrice")
    @ResponseBody
    public PageData editproperty() {
        logBefore(logger, "编辑property");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            /*String CHARGE_TYPES = "";
            String CHARGE_DATES = "";*/
           /* if(pd.get("data1[gdsr]") !=null && !"".equals(pd.get("data1[gdsr]"))){
                CHARGE_TYPES +=(pd.get("data1[gdsr]"));
            } if (pd.get("data1[cbsf]") !=null && !"".equals(pd.get("data1[cbsf]"))){
                CHARGE_TYPES +=(pd.get("data1[cbsf]"));
            } if (pd.get("data1[mjsf]") !=null && !"".equals(pd.get("data1[mjsf]"))){
                CHARGE_TYPES +=(pd.get("data1[mjsf]"));
            } if (pd.get("data1[tqrsf]") !=null && !"".equals(pd.get("data1[tqrsf]"))){
                CHARGE_DATES +=(pd.get("data1[tqrsf]"));
            } if (pd.get("data1[gdrsf]") !=null && !"".equals(pd.get("data1[gdrsf]"))){
                CHARGE_DATES +=(pd.get("data1[gdrsf]"));
            } if (pd.get("data1[cbhsf]") !=null && !"".equals(pd.get("data1[cbhsf]"))){
                CHARGE_DATES +=(pd.get("data1[cbhsf]"));
            }
            CHARGE_TYPES=CHARGE_TYPES.substring(0,CHARGE_TYPES.length()-1);
            CHARGE_DATES=CHARGE_DATES.substring(0,CHARGE_DATES.length()-1);*/

            PageData property1 = new PageData();//物业设置
            property1.put("ID", pd.get("data1[ID]"));//物业设置主键
            property1.put("CODE", pd.get("data1[CODE]")); //物业类型名称
           /* property1.put("CHARGE_DATE",CHARGE_DATES);*/ //物业创建时间*/
            /*property1.put("CHARGE_TYPE",CHARGE_TYPES); *///物业收费类型*/
            property1.put("INFO", pd.get("data1[INFO]")); //备注
            String id = property1.getString("ID");
            if (id.equals("a14e6f2e190e4492badac72e9b42152e") || id.equals("ddcf9b35bbe04cd88834e21c1fd74f32") || id.equals("669791dac4894160bc8d79b484519e96") || id.equals("7b05982a081e41deb9b46a1f6f5ed5fa")) {
                property1.put("IS_OPEN", "on"); //是否开启
            } else {
                property1.put("IS_OPEN", pd.get("data1[IS_OPEN]")); //是否开启
            }
            propertyService.editPropertySet(property1);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","编辑物业数据");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",property1.toString());
            recordService.SaveSystem(SystemPd);

            PageData price = new PageData();//物业价格
            JSONArray jsonArray = JSONArray.fromObject(pd); //获得jsonArray的第一个元素
            Object o2 = jsonArray.get(0);
            JSONObject jsonObject2 = JSONObject.fromObject(o2);
            Map map2 = JSONHelper.json2Map(jsonObject2.get("DATAS[DATA]").toString());
            Set<Object> keySet2 = map2.keySet();
            Iterator<Object> it2 = keySet2.iterator(); //有了Set集合。就可以获取其迭代器。
            while (it2.hasNext()) {
                Object key = it2.next();
                Object value = (Object) map2.get(key); //有了键可以通过map集合的get方法获取其对应的值。
                List<PageData> list2 = (List<PageData>) JSONArray.toList(JSONArray.fromObject(value.toString()), PageData.class);
                for (PageData stu : list2) {
                    /*System.out.println(stu.get("PRICE_IDS").toString());*/
                    if (stu.containsKey("PRICE_ID")) {
                        price.put("ID", stu.get("PRICE_ID").toString());//物业设置主键
                        price.put("PRICE_NAME", stu.get("PRICE_NAME").toString());//价格名称
                        price.put("PRICE_TYPE", stu.get("PRICE_TYPE").toString());//价格
                        propertyService.editPropertyPrice(price);
                    }
                    if(!stu.containsKey("PRICE_ID")) {
                        price.put("ID", this.get32UUID());//物业设置主键
                        price.put("IS_DEL", 0); //是否删除
                        price.put("SORT", 0); //排序
                        price.put("CREATE_ID", user.getUSER_ID()); //用户ID
                        price.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                        price.put("PRICE_NAME", stu.get("PRICE_NAME").toString());//价格名称
                        price.put("PRICE_TYPE", stu.get("PRICE_TYPE").toString());//价格
                       /* price.put("PRICE_CURRENCY", stu.get("PRICE_CURRENCY").toString());//价格类型*/
                        price.put("PROPERTY_SET_ID", pd.get("data1[ID]"));//物业设置ID
                        propertyService.savePropertyPrice(price);
                    }
                }
            }
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * 编辑物业设置
     */
    @RequestMapping(value = "/editPropertySet")
    @ResponseBody
    public PageData editPropertySet() {
        logBefore(logger, "编辑property开启");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {

            propertyService.editPropertySetOpen(pd);

            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","编辑物业数据");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);

            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 通过ID获取price详情信息
     */
    @RequestMapping(value = "/pricelist")
    @ResponseBody
    public PageData Pricelist() {
        logBefore(logger, "Price列表");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd.put("USER_ID",user.getUSER_ID());
            List<PageData> data = propertyService.PricelistAll(pd);//获取价格信息
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 获取所有的物业项
     */
    @RequestMapping(value = "/propertyList")
    @ResponseBody
    public PageData propertyList() {
        logBefore(logger, "获取所有的物业项");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            pd.put("USER_ID", user.getUSER_ID());
            List<PageData> list = propertyService.listAll(pd);
            res.put("data", list);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }
    /**
     * 获取所有的物业项 所有页面死值 修改
     */
    @RequestMapping(value = "/propertyListALL")
    @ResponseBody
    public PageData propertyListALL() {
        logBefore(logger, "获取所有的物业项");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            pd.put("USER_ID", user.getUSER_ID());
            List<PageData> list = propertyService.listAll(pd);
            res.put("data", list);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * 根据物业项ID获取物业项默认价格
     */
    @RequestMapping(value = "/propertyPriceList")
    @ResponseBody
    public PageData propertyPriceList() {
        logBefore(logger, "根据物业项ID获取物业项默认价格");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            List<PageData> list = propertyService.priceListAll(pd);
            res.put("data", list);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 删除物业设置和设置价格
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public PageData edit() {
        logBefore(logger, "删除property");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            PageData property1 = new PageData();//物业设置
            property1.put("ID", pd.get("ID"));//物业设置主键
            property1.put("IS_DEL", pd.get("IS_DEL"));
            propertyService.delPropertySet(property1);

            PageData price = new PageData();//物业价格
            price.put("CREATE_PERSON_ID",pd.get("ID"));//set表中的ID
            price.put("IS_DEL",pd.get("IS_DEL"));//价格类型
            propertyService.delPropertyPrice(price);

            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","删除物业设置数据");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",property1.toString());
            recordService.SaveSystem(SystemPd);

            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 删除价格
     */
    @RequestMapping(value = "/delPrice")
    @ResponseBody
    public PageData delPrice() {
        logBefore(logger, "删除property");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {

            propertyService.delPrice(pd);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","删除物业单价数据");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


}
